<?php

namespace App\Http\Middleware;

use Closure;
use App\Common\Api\SystemCode;
use App\Common\Api\SystemMessage;
use Tymon\JWTAuth\Facades\JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
use Exception;

class CheckLogin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        try {
            if (JWTAuth::parseToken()->authenticate()) {
                return $next($request);
            }
        } catch (Exception $e) {
            if ($e instanceof TokenExpiredException) {
                return response()->json([
                    'code' => SystemCode::SYSTEM_TOKEN_EXPIRED,
                    'message' => SystemMessage::SYSTEM_TOKEN_EXPIRED,
                    'data' => []
                ]);
            } else if ($e instanceof TokenInvalidException) {
                return response()->json([
                    'code' =>  SystemCode::SYSTEM_TOKEN_INVALID,
                    'message' =>SystemMessage::SYSTEM_TOKEN_INVALID,
                    'data' => []
                ]);
            } else if ($e instanceof JWTException) {
                return response()->json([
                    'code' => SystemCode::SYSTEM_TOKEN_NOT_EMPTY,
                    'message' => SystemMessage::SYSTEM_TOKEN_NOT_EMPTY,
                    'data' => []
                ]);
            }
        }
    }
}
